package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.sky.entity.Dish;
import com.sky.entity.Orders;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.Internal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class WorkspaceServiceImpl implements WorkspaceService {


    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;



    /**
     * 查询今日运营数据
     * ├─ newUsers	integer	必须		新增用户数
     * format: int32
     *
     * ├─ orderCompletionRate	number	必须		订单完成率
     * format: double
     *
     * ├─ turnover	number	必须		营业额
     * format: double
     *
     * ├─ unitPrice	number	必须		平均客单价
     * format: double
     *
     * ├─ validOrderCount	integer	必须		有效订单数
     * format: int32
     *
     * @return
     */
    @Override
    public BusinessDataVO businessData() {
        String today=LocalDate.now().toString();
        String nextDay= LocalDate.now().plusDays(1).toString();
        // 1.查询今日新增用户
        Integer newUsers = userMapper.getNewUserByCreateTime(today,nextDay);
        log.info("今日新增用户：{}",newUsers);
        // 2.订单完成率
        List<Orders> ordersListAll = ordersMapper.getByOrderTime(today, nextDay);
        List<Orders> ordersCompletionList = ordersListAll.stream().filter(orders -> orders.getStatus() == 5).collect(Collectors.toList());
        // 完成率
        double orderCompletionRate= (double) ordersCompletionList.size() /ordersListAll.size();
        orderCompletionRate=Double.parseDouble(String.format("%.2f", orderCompletionRate));
        log.info("今日完成率：{}",orderCompletionRate);
        // 3.营业额
        List<Double> doubleList=ordersMapper.getTurnoverByOrderTime(today,nextDay);
        Double turnover=doubleList.isEmpty() ? 0.0 : doubleList.stream().collect(Collectors.summingDouble(Double::doubleValue));
        log.info("今日营业额：{}",turnover);
        // 4.平均客单价
            // 查询今日的下单成功的用户总数
        Integer totalOrders=ordersMapper.getUserTotalByOrderTime(today,nextDay);
        Double unitPrice=turnover/totalOrders;// 平均客单价
        unitPrice=Double.parseDouble(String.format("%.2f", unitPrice));
        log.info("平均客单价：{}",unitPrice);
        // 5.有效订单数
        Integer validOrderCount=ordersCompletionList.size();
        log.info("有效订单数：{}",validOrderCount);

        return BusinessDataVO.builder()
                .newUsers(newUsers)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .unitPrice(unitPrice)
                .validOrderCount(validOrderCount).build();
    }


    /**
     * 查询套餐总览
     *  '售卖状态 0:停售 1:起售',
     *  ├─ discontinued	integer	必须		已停售套餐数量
     * format: int32
     *
     * ├─ sold	integer	必须		已启售套餐数量
     * format: int32
     * @return
     */
    @Override
    public SetmealOverViewVO overviewSetmeals() {
        List<Setmeal> list = setmealMapper.list(new Setmeal());
        if (ObjectUtil.isNotNull(list)&&list.size()>0){
            // 起售
            Integer sold= (int) list.stream().filter(setmeal -> setmeal.getStatus() == 1).count();
            // 停售
            Integer discontinued=list.size()-sold;
            log.info("查询到已停售套餐数量：{}",discontinued);
            return SetmealOverViewVO.builder()
                    .discontinued(discontinued)
                    .sold(sold).build();
        }
        return null;
    }


    /**
     * 查询菜品总览      `status` int DEFAULT '1' COMMENT '0 停售 1 起售
     *├─ discontinued	integer	必须		已停售菜品数量
     * format: int32
     *
     * ├─ sold	integer	必须		已启售菜品数量
     * format: int32
     * @return
     */
    @Override
    public DishOverViewVO overviewDishes() {
        List<Dish> list = dishMapper.list(null);
        if(ObjectUtil.isNotNull(list)&&list.size()>0){
            // 已起售菜品数量
            Integer sold=(int) list.stream().filter(dish -> dish.getStatus()==1).count();
            // 已停售菜品数量
            Integer discontinued=list.size()-sold;
            return DishOverViewVO.builder()
                    .discontinued(discontinued)
                    .sold(sold).build();
        }
        return null;
    }


    /**
     * 查询订单管理数据
     *    `status` int NOT NULL DEFAULT '1' COMMENT '订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款',
     *
     *    ├─ allOrders	integer	必须		全部订单
     * format: int32
     *
     * ├─ cancelledOrders	integer	必须		已取消数量
     * format: int32
     *
     * ├─ completedOrders	integer	必须		已完成数量
     * format: int32
     *
     * ├─ deliveredOrders	integer	必须		待派送数量
     * format: int32
     *
     * ├─ waitingOrders	integer	必须		待接单数量
     * format: int32
     * @return
     */
    @Override
    public OrderOverViewVO overviewOrders() {
        // 1.今日的全部订单
        List<Orders> ordersList = ordersMapper.getByOrderTime(LocalDate.now().toString(), LocalDate.now().plusDays(1).toString());
        //   `status` int NOT NULL DEFAULT '1' COMMENT '订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款',
        // 2.	全部订单
        int allOrders = ordersList.size();
        // 3.   已取消数量
        int cancelledOrders = (int)ordersList.stream().filter(orders -> Objects.equals(orders.getStatus(), Orders.CANCELLED)).count();
        // 4.   已完成数量
        int completedOrders = (int)ordersList.stream().filter(orders -> Objects.equals(orders.getStatus(), Orders.COMPLETED)).count();
        // 5.   待派送数量
        int deliveredOrders = (int)ordersList.stream().filter(orders -> Objects.equals(orders.getStatus(), Orders.CONFIRMED)).count();
        // 6.   待接单数量
        int waitingOrders = (int)ordersList.stream().filter(orders -> Objects.equals(orders.getStatus(), Orders.REFUND)).count();

        return OrderOverViewVO.builder()
                .allOrders(allOrders)
                .cancelledOrders(cancelledOrders)
                .completedOrders(completedOrders)
                .deliveredOrders(deliveredOrders)
                .waitingOrders(waitingOrders).build();
    }




    /**
     * 查询指定日期的运营数据
     * ├─ newUsers	integer	必须		新增用户数
     * format: int32
     *
     * ├─ orderCompletionRate	number	必须		订单完成率
     * format: double
     *
     * ├─ turnover	number	必须		营业额
     * format: double
     *
     * ├─ unitPrice	number	必须		平均客单价
     * format: double
     *
     * ├─ validOrderCount	integer	必须		有效订单数
     * format: int32
     *
     * @return
     */
    public BusinessDataVO getBusinessData(String today,String nextDay) {

        // 1.查询今日新增用户
        Integer newUsers = userMapper.getNewUserByCreateTime(today,nextDay);
        log.info("今日新增用户：{}",newUsers);
        // 2.订单完成率
        List<Orders> ordersListAll = ordersMapper.getByOrderTime(today, nextDay);
        List<Orders> ordersCompletionList = ordersListAll.stream().filter(orders -> orders.getStatus() == 5).collect(Collectors.toList());

        // 完成率
        double orderCompletionRate= ordersListAll.size()==0 ? 0.0 : (double) ordersCompletionList.size() /ordersListAll.size();
        orderCompletionRate=Double.parseDouble(String.format("%.2f", orderCompletionRate));
        log.info("今日完成率：{}",orderCompletionRate);
        // 3.营业额
        List<Double> doubleList=ordersMapper.getTurnoverByOrderTime(today,nextDay);
        Double turnover=doubleList.isEmpty() ? 0.0 : doubleList.stream().mapToDouble(Double::doubleValue).sum();
        log.info("今日营业额：{}",turnover);
        // 4.平均客单价
        // 查询今日的下单成功的用户总数
        Integer totalOrders=ordersMapper.getUserTotalByOrderTime(today,nextDay);
        Double unitPrice= totalOrders==0 ? 0.0 :turnover/totalOrders;// 平均客单价
        unitPrice=Double.parseDouble(String.format("%.2f", unitPrice));
        log.info("平均客单价：{}",unitPrice);
        // 5.有效订单数
        Integer validOrderCount=ordersCompletionList.size();
        log.info("有效订单数：{}",validOrderCount);

        return BusinessDataVO.builder()
                .newUsers(newUsers)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .unitPrice(unitPrice)
                .validOrderCount(validOrderCount).build();
    }





}
